<?php

namespace App\Service\users;

use App\Models\users\UsersAmountRecordModel;
use App\Models\users\UsersModel;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use lxs\config\BaseStatic;

class AccountRecordService extends BaseStatic
{

    const TYPE_WITHDRAW = 'users_withdraw_order'; // 提现
    const TYPE_ORDER = 'order'; // 订单
    const TYPE_ORDER_REFUND = 'order_refund';


    const USER_TOTAL = 'total_income';
    const USER_AMOUNT = 'amount';
    const USER_CREDIT = 'credit';

    /**
     * 用户金额记录表
     * @param int $uid 用户ID
     * @param float $num 金额正负值
     * @param string $credit_type 更新的字段
     * @param string $type 类型
     * @param int $table_id 表id
     * @param string $remark 备注
     * @param string $operator 操作人
     * @throws Exception
     */
    public function createAmountRecord(int $uid, float $num, string $credit_type, string $type, int $table_id, string $remark, string $operator='')
    {

        if ($num == 0) return false;

        $userInfo = UsersService::instance()->getUserInfo($uid);
        if (empty($userInfo)) {
            Log::error(Carbon::now()->toDateTimeString() . ' 插入用户金额记录表异常：用户不存在!');
            throw new Exception('插入用户金额记录表异常：用户不存在!');
        }

        if ( ($userInfo->$credit_type + $num) < 0 ) {
            Log::error(Carbon::now()->toDateTimeString() . ' 插入用户金额记录表异常：输入数值有误![' . $userInfo->$credit_type + $num . ']');
            throw new Exception('插入用户金额记录表异常：输入数值有误!');
        }

        $credit = max(0, $userInfo->$credit_type + $num);

        $data = [
            'uid' => $userInfo->id,
            'num' => $num,
            'credit_type' => $credit_type,
            'credits' => $credit,
            'type' => $type,
            'table_id' => $table_id,
            'remark' => $remark,
            'operator' => $operator,
            'create_time' => time()
        ];

        try {
            DB::beginTransaction();

            $userAmountRecordModel = new UsersAmountRecordModel();
            $userAmountRecordModel->fill($data);
            $userAmountRecordModel->save();

            if ($credit_type === self::USER_AMOUNT && $num > 0) {
                UsersModel::where('id', $userInfo->id)->update([$credit_type => $credit, self::USER_TOTAL => $userInfo->total_income + $num]);
            } else if ($credit_type === self::USER_AMOUNT && $num < 0) {
                UsersModel::where('id', $userInfo->id)->update([$credit_type => $credit, self::USER_TOTAL => $userInfo->total_income - abs($num)]);
            } else {
                UsersModel::where('id', $userInfo->id)->update([$credit_type => $credit]);
            }

            DB::commit();
            Log::info(Carbon::now()->toDateTimeString() . ' 插入用户金额记录表成功!');
        } catch (\Throwable $e) {
            Log::error(Carbon::now()->toDateTimeString() . ' 插入用户金额记录表异常：' . $e->getMessage() . $e->getLine());
            DB::rollBack();
            throw new Exception('插入用户金额记录表异常：' . $e->getMessage());
        }
    }

}
